package fm.dongman.animefm.view.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.widget.Toolbar;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import fm.dongman.animefm.R;
import fm.dongman.animefm.contractlib.contract.SettingContract;
import fm.dongman.animefm.view.activity.SingleActivity;
import fm.dongman.animefm.view.activity.WebViewActivity;
import fm.dongman.animefm.view.util.ActivityHelper;
import fm.dongman.animefm.view.util.SystemHelper;
import fm.dongman.animefm.view.util.ToastHelper;
import fm.dongman.animefm.view.widget.AnimeWatchSourceFeedbackDialog;
import fm.dongman.modellib.StaticArea.Injection;
import fm.dongman.modellib.model.FeedBackModel;
import fm.dongman.presenterlib.presenter.SettingPresenter;

import static fm.dongman.animefm.view.activity.SingleActivity.Companion;

/**
 * create by kuige,update from alex
 *
 * @description 设置页面
 */
public class SettingsFragment extends BaseFragment implements View.OnClickListener, SettingContract.ISettingView {

    private SettingContract.ISettingPresenter mPresenter;

    private ImageButton mIbClose;   //关闭按钮
    private TextView mTvClearCache;   //清除缓存
    private TextView mTvClearCacheSize; //缓存大小提示
    private TextView mTvCheckUpdate;   //检测版本
    private TextView mTvUpdateText;  //版本提示
    private TextView mTvOpenLib;    //开源库
    private TextView mTvFeedback;    //反馈
    private TextView mTvAbout;  //关于
    private TextView mTvQuitLogin;  //退出账号

    public SettingsFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layoutView = inflater.inflate(R.layout.fragment_settings, container, false);
        initView(layoutView);
        return layoutView;
    }

    /**
     * 初始化所有控件
     *
     * @param layoutView 布局view
     */
    private void initView(View layoutView) {

        mTvClearCache = (TextView) layoutView.findViewById(R.id.mTvSettingClearCache);
        mTvCheckUpdate = (TextView) layoutView.findViewById(R.id.mTvSettingCheckUpdate);
        mTvOpenLib = (TextView) layoutView.findViewById(R.id.mTvSettingOpenLibrary);
        mTvFeedback = (TextView) layoutView.findViewById(R.id.mTvSettingFeedback);
        mTvAbout = (TextView) layoutView.findViewById(R.id.mTvSettingAbout);
        mTvQuitLogin = (TextView) layoutView.findViewById(R.id.mTvSettingQuitLogin);
        mIbClose = (ImageButton) layoutView.findViewById(R.id.mIbSettingClose);
        mTvUpdateText = (TextView) layoutView.findViewById(R.id.mTvSettingUpdateText);
        mTvClearCacheSize = (TextView) layoutView.findViewById(R.id.mTvSettingClearCacheText);

        //设置ToolBar的paddingTop
        Toolbar toolbar = (Toolbar) layoutView.findViewById(R.id.mTbSettingToolBar);
        toolbar.setPadding(0, SystemHelper.INSTANCE.getStatusBarHeight(getActivity()), 0, 0);

        updateCacheSizeText();

        mTvCheckUpdate.setOnClickListener(this);
        mTvOpenLib.setOnClickListener(this);
        mTvFeedback.setOnClickListener(this);
        mTvAbout.setOnClickListener(this);
        mTvQuitLogin.setOnClickListener(this);
        mIbClose.setOnClickListener(this);
        mTvClearCache.setOnClickListener(this);
    }

    /**
     * 更新TextView，显示缓存大小
     */
    private void updateCacheSizeText() {
        //设置当前缓存大小
        mTvClearCacheSize.setText(getSize());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //清除缓存
            case R.id.mTvSettingClearCache:
                try {
                    if (Looper.myLooper() == Looper.getMainLooper()) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Glide.get(getActivity()).clearDiskCache();
                            }
                        }).start();
                    } else {
                        Glide.get(getActivity()).clearDiskCache();
                    }
                    Glide.get(getActivity()).clearMemory();
                    ToastHelper.getInstance(getActivity()).showSucceed("已清除" + "缓存");
                    updateCacheSizeText();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            //检测版本
            case R.id.mTvSettingCheckUpdate:
                ToastHelper.getInstance(getActivity()).showWarn("已是最新版本");
                break;

            //开源库
            case R.id.mTvSettingOpenLibrary:
                getActivity().startActivity(WebViewActivity.getIntent(getActivity(), "file:///android_asset/opensource.html", true));
                break;

            //反馈
            case R.id.mTvSettingFeedback:
                new AnimeWatchSourceFeedbackDialog.Builder(getActivity())
                        .setOnFeedbackListener(new AnimeWatchSourceFeedbackDialog.Builder.OnFeedBackListener() {
                            @Override
                            public void onCommit(Dialog dialog, int currentType, String content) {
                                //反馈相关信息
                                FeedBackModel feedBackModel = new FeedBackModel();
                                feedBackModel.setType(currentType);
                                feedBackModel.setContent(content);
                                //发送反馈
                                mPresenter.sendFeedBack(feedBackModel);
                                dialog.dismiss();
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();
                            }
                        })
                        .setTitle("反馈")
                        .setTypesAndId(
                                //类型 取值：0:视频播放；1:评论相关；2:按钮/链接；3:登录相关；4:图片相关；5:动漫信息；6:个人账户；7:其他；
                                new String[]{"视频播放",
                                        "评论相关",
                                        "按钮/链接",
                                        "登录相关",
                                        "图片相关",
                                        "动漫信息",
                                        "个人账户",
                                        "其他"},
                                new int[]{FeedBackModel.TYPE_VIDEO,
                                        FeedBackModel.TYPE_COMMENT,
                                        FeedBackModel.TYPE_BUTTON_OR_LINK,
                                        FeedBackModel.TYPE_LOGIN,
                                        FeedBackModel.TYPE_PIC,
                                        FeedBackModel.TYPE_COMMIC_INFO,
                                        FeedBackModel.TYPE_ACCOUNT,
                                        FeedBackModel.TYPE_OTHER})
                        .setIsMustHaveContent(true)
                        .build().show();
                break;

            //关于
            case R.id.mTvSettingAbout:
                Intent intent = new Intent(getActivity(), SingleActivity.class);
                intent.putExtra(Companion.getEXTRA_NAME(), Companion.getINTENT_EXTRA_ABOUT_US());
                ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
                break;

            //退出登陆
            case R.id.mTvSettingQuitLogin:
                mPresenter.logout();
                break;
            case R.id.mIbSettingClose:
                getActivity().onBackPressed();
                break;
        }
    }

    @Override
    public void initData() {
        new SettingPresenter(this, Injection.provideSettingRepository(getActivity()));
    }

    @Override
    public void bindData() {

    }

    @Override
    public void showVersion(@NotNull String url) {

    }

    @Override
    public void showNewVersion() {

    }

    @Override
    public void showAbout(@NotNull String url) {

    }

    @Override
    public void showFeedBackState(@NotNull String msg) {

    }

    @Override
    public void showLogout(boolean isLogout) {
        if (isLogout) {
            getActivity().sendBroadcast(new Intent().setAction(MyFragment.Companion.getINTENT_LOGIN()).putExtra(MyFragment.Companion.getINTENT_LOGIN_FLOG(), MyFragment.Companion.getINTENT_LOGIN_OUT()));
            getActivity().finish();
            ToastHelper.getInstance(getActivity()).showSucceed(" 退出登录成功");
        } else {
            ToastHelper.getInstance(getActivity()).showSucceed(" 你尚未登录");
        }

    }

    @Override
    public void showCacheCleaned(boolean isCleaned) {

    }

    @Override
    public void setPresenter(SettingContract.ISettingPresenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @NotNull
    @Override
    public Context getViewContext() {
        return getActivity();
    }

    @Override
    public void showNoNetwork() {

    }

    @Override
    public void showRefreshFailed() {

    }

    // 获取指定文件夹内所有文件大小的和
    private long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    private String getSize() {
        String str = "";
        try {
            str = Formatter.formatFileSize(getActivity(), getFolderSize(new File(getActivity().getApplication().getCacheDir() + "")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
}
